/**
*
* TÃ¢che pÃ©riodique sans mÃ©moire d'activation
*  Copyright (c) 2009 Ecole Centrale de Nantes IRCCyN
* see <a href="{@docRoot}/Documentation/task.html"> for more information</a>
* 
* @author: Richard
* @version 3.2
*/
package storm.Tasks;
import java.util.Iterator;
import storm.Entity;
import storm.EvtContext;
import storm.Timer;
import storm.Processors.LEATProcessor;
import storm.Processors.Processor;
import storm.Tasks.Task.Activation;
import log.TaskTrace;

/**
 * 
 * @author richard
 *
 */
public class PTask_NAM_TEST extends PTask {
	/**
	 * 
	 */
	public void rearmTimer(){
		super.rearmTimer();
		
		
	}
	/**
	 * 
	 */
	public void controleDealine(){
		super.controleDealine();
	}
	/**
	 * 
	 */
	public void inRunning() {
	
		/**
		 * Detection de la fin de traitement qui dÃ©passe la pÃ©riode
		 * dÃ©tection d'une exÃ©cution en dehors de la pÃ©riode  
		 */
		Processor P = this.getProcessor();
		if (P instanceof LEATProcessor){
			//Change frequency in time 
			LEATProcessor LP = (LEATProcessor) P;
			int freq = LP.getFreq() + 1 ;
			if (freq > 5) freq =0 ;
		 LP.setFreq(freq);
			
		}
		if(  (this.ET ==1 ) && (this.getRET()>=0 )) {
			
			for (int i = this.ActivationFIFO.size()-1 ; i != -1 ; i --){
				Activation E = (Activation) this.ActivationFIFO.get(i);
				if (!E.loseActivation){
						E.setDeb_exec(this.Kernel.getTime());
						break;
				
				}
			}
		}
		if(  (this.ET > 0 ) && (this.getRET()== 0)) {
			for (int i = this.ActivationFIFO.size()-1 ; i != -1 ; i --){
				Activation E = (Activation) this.ActivationFIFO.get(i);
				if (!E.loseActivation){
					if (E.getDeb_exec()>= 0) {
						E.setEnd_exec(this.Kernel.getTime());
						break;
					}
				}
			}
			
		}
		super.inRunning();
	}
	/**
	 * 
	 */
	public void onTick(){
		super.onTick();
		if (this.isnewPeriod) {
			Activation A = null;
			for (int i = this.ActivationFIFO.size()-1 ; i != -1 ; i --){
				Activation E = (Activation) this.ActivationFIFO.get(i);
				if (!E.loseActivation){
					A = E;
					break;
				}
			}
			/**
			 * récupére activation pas perdue 
			 */
			Activation B = new Activation(this.Kernel.getTime()+1);
			if (A.end_exec<0) {
				B.setLoseActivation(true);
			}
			this.ActivationFIFO.addLast(B);
			
			this.isnewPeriod = false;	
		}
		if (this.isDeadline) {
			Iterator I= this.ActivationFIFO.iterator();
			while (I.hasNext()) {
				Activation A = (Activation) I.next();
				if (A.getDeadline() <0){
					A.setDeadline(this.Kernel.getTime()+1);
					//miss deadline
					if ((A.end_exec<0)&&(!A.loseActivation))  this.Kernel.getLogs().addTrace(new TaskTrace(this.Kernel.getTime(),this, TaskTrace.Type.FAILED,A.getDate()));
 					break;
				}
			}
			this.isDeadline = false;	
		}
	}

}

